//
//  LQRequestApi.m
//  BaseProject
//
//  Created by 喻飞 on 15/5/21.
//  Copyright (c) 2015年 yuf. All rights reserved.
//

#import "LQRequestApi.h"
#import <Ono/Ono.h>
@implementation LQRequestApi
@synthesize  engine,delegate;

static    MKNetworkEngine *engine=nil;

static NSMutableDictionary* _children;

-(id)init//thread-safe
{
    //生成一个 单例
    self.engine= [LQRequestApi shareEngine];
    
    return  self ;
}



// this is good
+ (LQRequestApi *)sharedInstance
{
    static LQRequestApi *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[LQRequestApi alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

+(MKNetworkEngine *)shareEngine:(NSString *)hostName{
    static    MKNetworkEngine *engine=nil;
    @synchronized(self)
    {
        if(engine == nil)
            
        {
            engine = [[MKNetworkEngine alloc] initWithHostName:hostName];
            //HOST——URL是被发送请求的主机地址
        }
    }
    return engine;
}
+(MKNetworkEngine *)shareEngine{
    static    MKNetworkEngine *engine=nil;
    @synchronized(self)
    {
        if(engine == nil)
            
        {
            engine = [[MKNetworkEngine alloc] initWithHostName:IP_Address_Fresh];
            //HOST——URL是被发送请求的主机地址
        }
    }
    return engine;
}
#pragma mark   MKNetworkOperation
/*
 dic   传递的参数
 type   传递方式  POST GET
 interface_Path  接口路径
 */

-(void)requestOperationWithDic:(NSMutableDictionary  *)dic  withPath:(NSString *)interface_Path  withHttpType:(NSString *)type  withTag:(NSInteger )tag{
    
    
    // dic=[Common   postBasicReqestArgs:dic];
    
    if (!self.engine) {
        if([interface_Path isEqualToString:@"/uploadImg.do"]){
            self.engine= [LQRequestApi shareEngine:IP_Address_ImageDown_Fresh];
        }else{
                self.engine= [LQRequestApi shareEngine:IP_Address_Fresh];
        }
        
    }
    self.engine = nil;
    if ([interface_Path isEqualToString:SX_IP]) {
        self.engine= [LQRequestApi shareEngine:IP_Address_NAV];
    }else{
        self.engine= [LQRequestApi shareEngine:IP_Address_Fresh];

    }
    
    [engine useCache];
    
    //最后的斜杠不能丢掉，不然会出问题
    MKNetworkOperation *operation;
    
    if ([type  isEqualToString:@"POST"]) {
        //最后的斜杠不能丢掉，不然会出问题@"/yii/testApp/index.php?r=httpTest/getTest/"
        operation = [engine operationWithPath:interface_Path
                                       params:dic
                                   httpMethod:type];
        
    }else{// GET
        operation = [engine operationWithPath:interface_Path
                                       params:dic
                                   httpMethod:type];
    }
    
    
    //    NSLog(@"传递的参数 %@",dic);
//    [Common setControllerDelegate:delegate];
    [operation addCompletionHandler:^(MKNetworkOperation *completedOperation)
     {
         if ([interface_Path isEqualToString:SX_IP]) {
         NSError *error = nil;
         NSString *xmlString =[completedOperation responseString];
         NSData *xmlData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];
         ONOXMLDocument *document = [ONOXMLDocument XMLDocumentWithData:xmlData error:&error];
         ONOXMLElement *firstElementX = [document.rootElement firstChildWithTag:@"posX"];
         ONOXMLElement *firstElementY = [document.rootElement firstChildWithTag:@"posY"];
         ONOXMLElement *firstElementlocID = [document.rootElement firstChildWithTag:@"locID"];
         ONOXMLElement *firstElementlocName = [document.rootElement firstChildWithTag:@"locName"];
         NSString *posX = [firstElementX stringValue];
         NSString *posY = [firstElementY stringValue];
         NSString *locID = [firstElementlocID stringValue];
         NSString *locName = [firstElementlocName stringValue];
         NSMutableDictionary *data = [NSMutableDictionary dictionary];
         if ([posX integerValue] > 0) {
             [data setObject:posX forKey:@"posX"];
             [data setObject:posY forKey:@"posY"];
             [data setObject:locID forKey:@"locID"];
             [data setObject:locName forKey:@"locName"];
             if ([delegate  respondsToSelector:@selector(fetchDatabaseFinished:withTag:)]) {
                 
                 [delegate fetchDatabaseFinished:data withTag:tag];
             }
         }
        }
//         
         if([completedOperation isCachedResponse]) {
             
             //             NSLog(@"Data from cache %@", [completedOperation responseString]);
             
             NSString *jsonString =[completedOperation responseString];
             
             NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
             NSError *error = nil;
             NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
             if (!delegate) {
                 delegate = [Common getControllerDelegate];
             }
             if ([delegate  respondsToSelector:@selector(fetchDatabaseFinishedFromCache:withTag:)]) {
                 
                 [delegate fetchDatabaseFinishedFromCache:dictionary withTag:tag];
             }
             
         }
         else {
             
             NSString *jsonString =[completedOperation responseString];
             
             //NSLog(@"jsonString   %@",jsonString);
             //             if ( tag == ScannHappy_kPublishDetailTag ) {
             //
             //                 jsonString=[jsonString substringWithRange:NSMakeRange(1, jsonString.length-2)];
             //
             //             }else{
             //
             //                 jsonString=[jsonString stringByReplacingOccurrencesOfString:@"[" withString:@""];
             //                 jsonString=[jsonString stringByReplacingOccurrencesOfString:@"]" withString:@""];
             //             }
             //NSLog(@"responseString %@",jsonString);
             
             NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
             NSError *error = nil;
             NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
             if (!delegate) {
                 delegate = [Common getControllerDelegate];
             }
             if ([delegate  respondsToSelector:@selector(fetchDatabaseFinished:withTag:)]) {
                 
                 [delegate fetchDatabaseFinished:dictionary withTag:tag];
             }
             
         }
         
     }errorHandler:^(MKNetworkOperation *errorOp, NSError* error) {
         
         NSLog(@"error -==>%@",error);
         if ([delegate  respondsToSelector:@selector(fetchDatabaseFailed:message:)]) {
             
             [delegate  fetchDatabaseFailed:error message:@""];
         }
     }];
//
    [engine enqueueOperation:operation];
    
}
@end
